import { onMounted, nextTick, ref, reactive, watch } from "vue";
import axios from "axios";
import * as echarts from "echarts";
import mitt from "@/assets/js/mitt.js";
import { dayjs } from "element-plus";

const url = import.meta.env.VITE_backurl;
const urlYbd = import.meta.env.VITE_backurl_java;
const urlGif = import.meta.env.VITE_backurl_gif;
const urlJxh=import.meta.env.VITE_backurl_jxh;

mitt.on("dateChangeMap", (value) => {
  tempDate.value = value;
});

export const uploadFile = (data) => {
  return axios({
    method: "post",
    url: url + "/fore/upload",
    data: data.file,
  });
};

export const getFileList = (data) => {
  return axios({
    method: "get",
    url: url + "/fore/getFileList",
    params: {
      time: data.time,
    },
  });
};

export const uploadFileTide = (data) => {
  return axios({
    method: "post",
    url: url + "/up/uploadRbr",
    params: {
      numOffset: data.numOffset,
    },
    data: data.file,
  });
};

export const uploadFileFb = (data) => {
  return axios({
    method: "post",
    url: url + "/up/uploadFb",
    data: data.file,
  });
};

export const initList = (data) => {
  return axios({
    method: "get",
    url: url + "/wz/getForeList",
    params: data,
  });
};

export const getDetail = (data) => {
  return axios({
    method: "get",
    url: url + "/wz/getForeDetail",
    params: data,
  });
};

export const getForeTable = (data) => {
  return axios({
    method: "get",
    url: url + "/wz/getForeTable",
    params: data,
  });
};

export const subForeData = (data) => {
  return axios({
    method: "post",
    url: url + "/wz/submitForeData",
    params: {
      id: data.id,
      time: data.time,
    },
    data: data.data,
  });
};

export const filePreview = (data) => {
  return axios({
    method: "get",
    url: url + "/word/" + data.name,
    responseType: "blob",
  });
};

export const lookFore = (data) => {
  return axios({
    method: "get",
    // url: url + '/word/浅滩堤防保障预报20230614.docx',
    url: url + "/ybd/" + data.name,
    params: {
      time: new Date().getTime(),
    },
    responseType: "blob",
  });
};

export const lookPdf = (data) => {
  return axios({
    method: "get",
    url: url + "/word/浅滩堤防保障预报20230614.pdf",
    responseType: "blob",
    params: {
      time: new Date().getTime(),
    },
  });
};

// 生成预报单
export const createFore = (data) => {
  return axios({
    method: "post",
    url: urlYbd + "/ybd",
    data: data.data,
  });
};

export const createForeXlsx = (data) => {
  return axios({
    method: "post",
    url: url + "/createForeXlsx",
    data: data.data,
    params: {
      type: data.type,
      fileName: data.fileName,
    },
  });
};

export const updateFore = (data) => {
  return axios({
    method: "post",
    url: url + "/wz/updateFore",
    params: data,
  });
};

export const updateForeDetail = (data) => {
  return axios({
    method: "post",
    url: url + "/wz/updateForeDetail",
    data: data,
  });
};

export const getDetailLast = (data) => {
  return axios({
    method: "get",
    url: url + "/wz/getForeDetailLast",
    params: data,
  });
};

export const sendFore = (data) => {
  return axios({
    method: "post",
    url: url + "/wz/sendFore",
    data: data,
  });
};

export const sendEmail = (data) => {
  return axios({
    method: "post",
    url: urlYbd + "/mailbox",
    data: data,
  });
};

export const initChartService = async (dom, row, time, idx,min=-4,max=6) => {
  let date = formatDate(getAfterDate(time, idx), "YYYY-MM-DD");
  let p = null;
  let fileName = "";
  await getTideByHour({
    date: formatDate(getAfterDate(time, idx), "YYYY-MM-DD"),
    station: '玉寮',
  }).then(async (res) => {
    let finalData = {
      hourTide: [],
      highLowTide: [],
    };
    let data = res.data.data;
    let zhushi = data.map((item) => {
      // return [item.date + " " + item.time, item.tide];
      return {
        time: item.time,
        value: item.tide,
        isHighLow: false,
      };
    });
    finalData.hourTide = zhushi;

    for (let i = 0; i < row.length; i++) {
      if (i % 2 != 0) {
        finalData.highLowTide.push(
          //   [
          //   date + " " + row[i].value,
          //   row[i + 1].value,
          // ]
          {
            time: row[i].value,
            value: row[i + 1].value,
            isHighLow: true,
          }
        );
      }
    }

    let title=""
    if(!dom.includes('_')){
      title=date+' 潮汐预报'
    }
    finalData=JSON.parse(JSON.stringify(finalData))
    let result = await initChart(document.getElementById(dom), finalData,title,min,max);
    let fileResult = result.file;
    fileName = result.fileName;
    let formData = new FormData();
    formData.append("file", fileResult);
    if(dom.includes('_')){
      p = savaPng(formData);
    }
    // allP.push(savaPng(formData))
    // savaPng(formData).then((res) => {
    //   console.log(res);
    // });
  });
  return {
    p: p,
    fileName: fileName,
  };
};

export const savaPng = (data) => {
  return axios({
    method: "post",
    url: url + "/fore/savePng",
    data: data,
  });
};

export const deletePng = (data) => {
  return axios({
    method: "post",
    url: url + "/fore/deletePng",
    params: data,
  });
}

export const initChartTide = (dom, data, domId) => {
  data.highLowTide.forEach((item) => {
    item.isHighLow = true;
  });
  data.hourTide.forEach((item) => {
    item.isHighLow = false;
  });
  let finalData = [...data.highLowTide, ...data.hourTide].sort((a, b) => {
    let aArr = a.time.split(":");
    let bArr = b.time.split(":");
    return aArr[0] - bArr[0] || aArr[1] - bArr[1];
  });
  let myChart;
  let option = {
    xAxis: {
      type: "category",
      data: data.xAll,
    },
    yAxis: {
      type: "value",
    },
    tooltip: {
      trigger: "axis",
    },
    grid: {
      left: "3%",
      right: "4%",
      bottom: "3%",
      top: "15%",
      containLabel: true,
    },
    series: [
      {
        // data: data.highLowTide.map(item => [item.time,item.value]),
        data: finalData.map((item) => [item.time, item.value, item.isHighLow]),
        type: "line",
        smooth: true,
        // isHighLow为true时，显示点要素和数值，否则不显示
        // symbol: (params) => {
        //   if (params[2]) {
        //     return 'circle'
        //   } else {
        //     return 'none'
        //   }
        // },
        // symbolSize: (params) => {
        //   if (params[2]) {
        //     return 10
        //   } else {
        //     return 0
        //   }
        // },
        label: {
          show: false,
          position: "top",
          formatter: (params) => {
            if (params.data[2]) {
              return params.data[1];
            } else {
              return "";
            }
          },
        },
        // 不显示点
        showSymbol: false,
      },
      {
        data: data.highLowTide.map((item) => [item.time, item.value]),
        type: "scatter",
        symbolSize: 10,
        // 最高层级
        z: 10,
        label: {
          show: true,
          position: "top",
          formatter: (params) => {
            return params.data[1];
          },
        },
        // 不显示tooltip
        tooltip: {
          show: false,
        },
      },
    ],
  };
  // if (myChart) {
  //   myChart.dispose()
  // }
  myChart = echarts.init(dom);
  myChart.setOption(option);
};

export const getWaveRange = (data) => {
  return axios({
    method: "post",
    url: urlGif + "/seriesQueries",
    params: {
      aaa: new Date().getTime(),
    },
    data: data,
  });
};

export const getWaveRangeSa = (data) => {
  return axios({
    method: "post",
    url: urlJxh + "/sanaoVisualizationBack-1.0/seriesQueries?",
    // url:'http://www.wzhy.com.cn:8000/sanaoVisualizationBack-1.0/seriesQueries',
    // params: {
    //   aaa: new Date().getTime(),
    // },
    data: data,
  });
};

export const tempDate = ref("");

export const hours = [
  {
    value: 0,
    label: "00",
  },
  {
    value: 1,
    label: "01",
  },
  {
    value: 2,
    label: "02",
  },
  {
    value: 3,
    label: "03",
  },
  {
    value: 4,
    label: "04",
  },
  {
    value: 5,
    label: "05",
  },
  {
    value: 6,
    label: "06",
  },
  {
    value: 7,
    label: "07",
  },
  {
    value: 8,
    label: "08",
  },
  {
    value: 9,
    label: "09",
  },
  {
    value: 10,
    label: "10",
  },
  {
    value: 11,
    label: "11",
  },
  {
    value: 12,
    label: "12",
  },
  {
    value: 13,
    label: "13",
  },
  {
    value: 14,
    label: "14",
  },
  {
    value: 15,
    label: "15",
  },
  {
    value: 16,
    label: "16",
  },
  {
    value: 17,
    label: "17",
  },
  {
    value: 18,
    label: "18",
  },
  {
    value: 19,
    label: "19",
  },
  {
    value: 20,
    label: "20",
  },
  {
    value: 21,
    label: "21",
  },
  {
    value: 22,
    label: "22",
  },
  {
    value: 23,
    label: "23",
  },
];

// getTideByHour
export const getTideByHour = (data) => {
  return axios({
    method: "get",
    url: url + "/wz/getTideByHour",
    params: data,
  });
};

// testPng
export const testPng = (data) => {
  return axios({
    method: "get",
    url: url + "/img/" + data.name,
    responseType: "blob",
  });
};

export const testPngSa = (data) => {
  return axios({
    method: "get",
    url: url + "/imgSa/" + data.name,
    responseType: "blob",
  });
};

// getLastWeek
export const getLastWeek = (data) => {
  return axios({
    method: "get",
    url: url + "/wz/getLastWeek",
  });
};

// 获取一个日期第n天后的日期
export const getAfterDate = (date, n) => {
  const d = new Date(date);
  d.setDate(d.getDate() + n);
  return d;
};

// 任意方式格式化日期
export const formatDate = (date, format) => {
  return dayjs(date).format(format);
};

export const initChart = async (chartDom, data,title='',min,max) => {
  // let min=Math.min(...data.highLowTide.map(item=>item.value))
  // let max=Math.max(...data.highLowTide.map(item=>item.value))
  // min=Math.floor(min)-1
  // max=Math.ceil(max)+1
  data.highLowTide.forEach((item) => {
    item.isHighLow = true;
  });
  data.hourTide.forEach((item) => {
    item.isHighLow = false;
  });
  let finalData = [...data.highLowTide, ...data.hourTide].sort((a, b) => {
    let aArr = a.time.split(":");
    let bArr = b.time.split(":");
    return aArr[0] - bArr[0] || aArr[1] - bArr[1];
  });

  // let myChart
  let option = {
    // 不显示动画
    animation: false,
    grid: {
      // top: 20,
      left: '50%',
      // right: 20,
      // bottom: 20,
    },
    title: {
      text: title,
      left: "center",
      // 字体
      textStyle: {
        // fontSize: 14,
        fontWeight: "normal",
        fontFamily: "钉钉进步体",
      },
      show : title ? true : false,
      top: 'top',
    },
    xAxis: [
      {
        type: "time",
        show: true,
        // 最下方
        position: "bottom",
        // 格式化，只显示小时和分钟
        axisLabel: {
          formatter: function (value, index) {
            var date = new Date(value);
            var hours = date.getHours();
            var minutes = date.getMinutes();
            if (hours < 10) hours = "0" + hours;
            if (minutes < 10) minutes = "0" + minutes;
            // return hours + ":" + minutes;
            return hours + "时"
          },
        },
        // 不显示刻度
        axisTick: {
          show: true,
        },
      },
      {
        type: "time",
        show: false,
        position: "top",
        // 格式化，只显示小时和分钟
        axisLabel: {
          show: false,
          formatter: function (value, index) {
            var date = new Date(value);
            var hours = date.getHours();
            var minutes = date.getMinutes();
            if (hours < 10) hours = "0" + hours;
            if (minutes < 10) minutes = "0" + minutes;
            // return hours + ":" + minutes;
            return hours + "时";
          },
        },
        // 不显示刻度
        axisTick: {
          show: true,
        },
      },
    ],
    yAxis: [
      {
        type: "value",
        show: true,
        axisLine: {
          show: true,
        },
        //范围-5到6
        min: min,
        max: max,
        // 在左侧中间显示名称
        nameLocation: "middle",
        nameGap: 20,
        name: "潮位(m)",
        // 显示刻度，向内，只显示偶数数值和刻度
        axisTick: {
          show: true,
          inside: true,
          alignWithLabel: true,
          interval: 2,
        },
        // 显示刻度
        axisLabel: {
          show: true,
        },
      },
      {
        type: "value",
        show: true,
        position: "right",
        axisLine: {
          show: true,
        },
        //范围-5到6
        min: min,
        max: max,
        // 显示刻度，向内，只显示偶数数值和刻度
        axisTick: {
          show: true,
          inside: true,
          alignWithLabel: true,
          interval: 2,
        },
      },
    ],
    tooltip: {
      trigger: "axis",
      // 显示小时和分钟
      formatter: (params) => {
        return (
          "时间: " +
          params[0].value[0].split(" ")[1] +
          "</br>" +
          "潮位: " +
          params[0].value[1]
        );
        // 换行
      },
    },
    grid: {
      left: "3%",
      right: "4%",
      bottom: title?'13%':'3%',
      top: title?'20%':'15%',
      containLabel: true,
    },
    series: [
      {
        data: finalData.map((item) => [
          "2023-05-05 " + item.time,
          item.value,
          item.isHighLow,
        ]),
        type: "line",
        smooth: true,
        label: {
          show: false,
          position: "top",
          formatter: (params) => {
            if (params.data[2]) {
              return params.data[1];
            } else {
              return "";
            }
          },
        },
        yAxisIndex: 0,
        xAxisIndex: [0, 1],
        // 点显示为实心圆
        symbol: "circle",
      },
      {
        data: data.highLowTide.map((item) => [
          "2023-05-05 " + item.time,
          item.value,
        ]),
        type: "scatter",
        symbolSize: 10,
        // 最高层级
        z: 10,
        label: {
          show: true,
          position: "top",
          formatter: (params) => {
            // return params.data[1] + "\n" + params.data[0].split(" ")[1];
            return params.data[0].split(" ")[1] + "\n" + params.data[1];
          },
          // color: "#0E5CA7",
          // 字体大小10px,加粗
          fontSize: 10,
          fontWeight: "bold",
        },
        // 数值正点为红色，负点为蓝色
        itemStyle: {
          color: (params) => {
            if (params.data[1] > 0) {
              return "#D0021B";
            } else {
              return "#7ED321";
            }
          },
        },
        yAxisIndex: 0,
        xAxisIndex: [0, 1],
        // // 不显示tooltip
        // tooltip: {
        //   show: false,
        // },
      },
      {
        data: finalData.map((item) => [
          "2023-05-05 " + item.time,
          -2,
        ]),
        type: "line",
        smooth: true,
        // 不显示点
        showSymbol: false,
        // 红色
        // itemStyle: {
        //   color: "#d0021b",
        // },
        lineStyle: {
          color: "#d0021b",
          width: 1,
        },
      }
    ],
  };

  let myChart = echarts.init(chartDom);
  myChart.setOption(option);
  await nextTick();
  // allPic["image" + i] = myChart[i].getDataURL({ pixelRatio: 2, });
  // return myChart.getDataURL({ pixelRatio: 2 });
  // return base64DataURLToArrayBuffer(myChart.getDataURL({ pixelRatio: 2 }));
  // let file = new File([blob], fileName, { type: "image/png" })
  // let formData = new FormData();

  let fileBase64 = myChart.getDataURL({ pixelRatio: 2 });
  // 转为blob
  let blob = base64ToBlob(fileBase64);
  let fileName = Date.now() + ".png";
  let file = new File([blob], fileName, { type: "image/png" });
  return {
    file: file,
    fileName: fileName,
  };
};

const base64DataURLToArrayBuffer = (dataURL) => {
  const base64Regex = /^data:image\/(png|jpg|svg|svg\+xml);base64,/;
  if (!base64Regex.test(dataURL)) {
    return false;
  }
  const stringBase64 = dataURL.replace(base64Regex, "");
  let binaryString;
  if (typeof window !== "undefined") {
    binaryString = window.atob(stringBase64);
  } else {
    binaryString = new Buffer(stringBase64, "base64").toString("binary");
  }
  const len = binaryString.length;
  const bytes = new Uint8Array(len);
  for (let i = 0; i < len; i++) {
    const ascii = binaryString.charCodeAt(i);
    bytes[i] = ascii;
  }
  return bytes.buffer;
};

const base64ToBlob = (code) => {
  let parts = code.split(";base64,");
  let contentType = parts[0].split(":")[1];
  let raw = window.atob(parts[1]);
  let rawLength = raw.length;
  let uInt8Array = new Uint8Array(rawLength);
  for (let i = 0; i < rawLength; ++i) {
    uInt8Array[i] = raw.charCodeAt(i);
  }
  return new Blob([uInt8Array], { type: contentType });
};

const fileNameMap = {
  hx: "浅滩航线保障预报",
  hy: "浅滩海域风浪预报",
  df: "浅滩堤防保障预报",
  zb: "浅滩一周海洋环境预报",
};
const fileNameMap1 = {
  sa: "三澳日预报",
  sz: "三澳周预报",
  dt: "洞头紫菜养殖海洋预报",
  dtzb: "洞头紫菜养殖周预报",
};
export const getFileName = (data) => {
  let timeStr = data.time.split("-").join("");
  if (Object.keys(fileNameMap).includes(data.type)) {
    return fileNameMap[data.type] + timeStr;
  } else if (Object.keys(fileNameMap1).includes(data.type)) {
    let date = new Date(data.time);
    let firstDay = new Date(date.getFullYear(), 0, 1);
    let diff = (date - firstDay) / 1000 / 60 / 60 / 24 + 1;
    let year = date.getFullYear();
    let week = Math.ceil(diff / 7);
    if (fileNameMap1[data.type].includes("周")) {
      return `${fileNameMap1[data.type]}（${year}年第${Math.floor(week)}期）`;
    } else {
      return `${fileNameMap1[data.type]}（${year}年第${Math.floor(diff)}期）`;
    }
  } else if (data.type == "yy") {
    let es = data.name.includes("24") ? "24" : "48";
    return `温州海洋渔业专项保障预报-${es}_${timeStr + data.hour}_${es}`;
  } else if (data.type == "rahx") {
    // let es = data.name.match(/\d+/g)[0];
    let es = data.name.split('航线')[1]
    return `瑞安沿海重点航线海洋预报${timeStr.slice(4, 8)}——${es}小时`;
  } else if (data.type == "rayg") {
    // let es = "";
    // if (data.name.includes("24")) {
    //   es = "24";
    // } else if (data.name.includes("48")) {
    //   es = "48";
    // } else if (data.name.includes("72")) {
    //   es = "72";
    // }
    let es = data.name.split('港口')[1]
    return `瑞安沿海重点渔港海洋预报${timeStr.slice(4, 8)}——${es}小时`;
  } else if (data.type == "wzhy") {
    return `温州海洋预报_${timeStr + data.hour}00`;
  } else if (data.type == "wzhx") {
    return `温州沿海航线预报${timeStr + data.hour}`;
  } else if (data.type == "hdrc") {
    return `海钓指数和日出时间预报_${timeStr}`;
  } else if (data.type == "hsyc") {
    return `温州海水浴场环境预报_${timeStr}15`;
  } else if (data.type == "nj") {
    return `南麂航线海洋预报${timeStr.slice(4, 8)}——72小时`;
  } else if (data.type == "fb") {
    return `wz_waveh_${timeStr}`;
  } else if(data.type == "ydyl"){
    return `温州市海洋预报台${timeStr}`
  }else if(data.type == "pyja"){
    return `平阳近岸海域预报${timeStr.slice(4, 8)}`
  }
  return ``;
};

// 根据任意格式获取当前日期
export const getNowDate = (format="YYYY-MM-DD") => {
  return dayjs().format(format);
};